"""
管理后台 - 案例管理接口
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_db, get_current_user
from app.schemas.common import ResponseModel, PaginatedResponse
from app.schemas.content import CaseCreate, CaseUpdate, CaseResponse
from app.crud.base import CRUDBase
from app.models.content import Case


router = APIRouter()
crud_case = CRUDBase[Case, CaseCreate, CaseUpdate](Case)


@router.get("", response_model=ResponseModel)
async def get_cases(
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    industry: Optional[str] = Query(None),
    status: Optional[int] = Query(None),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取案例列表
    """
    filters = {}
    if industry:
        filters["industry"] = industry
    if status is not None:
        filters["status"] = status
    
    skip = (page - 1) * page_size
    cases = await crud_case.get_multi(db, skip=skip, limit=page_size, filters=filters)
    total = await crud_case.get_count(db, filters=filters)
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=[CaseResponse.model_validate(c) for c in cases]
        )
    )


@router.get("/{case_id}", response_model=ResponseModel)
async def get_case(
    case_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取案例详情
    """
    case = await crud_case.get_by_id(db, id=case_id)
    if not case:
        raise HTTPException(status_code=404, detail="案例不存在")
    
    return ResponseModel(data=CaseResponse.model_validate(case))


@router.post("", response_model=ResponseModel)
async def create_case(
    case_in: CaseCreate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    创建案例
    """
    case = await crud_case.create(db, obj_in=case_in)
    return ResponseModel(
        code=201,
        message="创建成功",
        data=CaseResponse.model_validate(case)
    )


@router.put("/{case_id}", response_model=ResponseModel)
async def update_case(
    case_id: int,
    case_in: CaseUpdate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    更新案例
    """
    case = await crud_case.get_by_id(db, id=case_id)
    if not case:
        raise HTTPException(status_code=404, detail="案例不存在")
    
    case = await crud_case.update(db, db_obj=case, obj_in=case_in)
    return ResponseModel(
        message="更新成功",
        data=CaseResponse.model_validate(case)
    )


@router.delete("/{case_id}", response_model=ResponseModel)
async def delete_case(
    case_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    删除案例
    """
    success = await crud_case.delete(db, id=case_id)
    if not success:
        raise HTTPException(status_code=404, detail="案例不存在")
    
    return ResponseModel(message="删除成功")

